package com.example.distortionmeter

//import android.bluetooth.BluetoothManager
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.material3.MaterialTheme
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.WindowCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle

import com.example.distortionmeter.ui.home.MainScreen
import com.example.distortionmeter.domain.BluetoothManager
import com.example.distortionmeter.ui.theme.DistortionMeterTheme
import com.example.distortionmeter.viewmodel.DistortionViewModel
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
    // 将 ViewModel 声明为成员变量
    private lateinit var viewModel: DistortionViewModel

    // 防抖且顺序显示的Toast工具
    private var toastQueue = mutableListOf<String>()
    private var isShowingToast = false


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        viewModel = ViewModelProvider(this)[DistortionViewModel::class.java]
        viewModel.setPermissionCallback { perms, requestCode ->
            ActivityCompat.requestPermissions(this, perms, requestCode)
        }
        viewModel.initBluetoothManager(this)



        setContent {
            MaterialTheme {
                MainScreen(viewModel)
            }
        }

        lifecycleScope.launch {
            viewModel.bluetoothErrors.collect { error ->
                showSequentialToast(error)
            }
        }
    }

    // ============= 工具方法 =============
    // 顺序显示 Toast 的具体实现（类成员方法）
    private fun showSequentialToast(msg: String) {
        toastQueue.add(msg)
        if (!isShowingToast) {
            isShowingToast = true
            showNextToast()
        }
    }
    private fun showNextToast() {
        if (toastQueue.isNotEmpty()) {
            val msg = toastQueue.removeAt(0)
            Toast.makeText(this, msg, Toast.LENGTH_LONG).apply {
                addCallback(object : Toast.Callback() {
                    override fun onToastHidden() {
                        super.onToastHidden()
                        isShowingToast = false
                        showNextToast()
                    }
                })
                show()
            }
        }
    }
    // 检查蓝牙权限
    @SuppressLint("MissingPermission")
    private fun checkBluetooth() {
            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            ActivityCompat.startActivityForResult(this,enableBtIntent,BluetoothManager.REQUEST_ENABLE_BT,null)
    }

    // 处理权限请求结果
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        // 通知 ViewModel 权限结果
        if (requestCode == BluetoothManager.REQUEST_BLUETOOTH) {
            val allGranted = grantResults.all { it == PackageManager.PERMISSION_GRANTED }
            if (allGranted) {
                // 权限已授予，可以继续操作（如重新尝试扫描）
                viewModel.startScan()
            } else {
                // 权限被拒绝，提示用户
                Toast.makeText(this, "权限被拒绝，蓝牙功能不可用", Toast.LENGTH_SHORT).show()
            }
        }
    }
}
